package com.xjc.service.impl;

import com.xjc.common.utils.R;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xjc.common.utils.PageUtils;
import com.xjc.common.utils.Query;

import com.xjc.dao.CategoryDao;
import com.xjc.entity.CategoryEntity;
import com.xjc.service.CategoryService;

import javax.annotation.Resource;


@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {

    @Resource
    CategoryDao categoryDao;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CategoryEntity> page = this.page(
                new Query<CategoryEntity>().getPage(params),
                new QueryWrapper<CategoryEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public List<CategoryEntity> queryCategoryWithChildren() {
        List<CategoryEntity> all= categoryDao.selectList(null);

        List<CategoryEntity> root= all.stream().filter(categoryEntity -> categoryEntity.getParentCid()==0)
                .sorted((o1, o2) -> {
                    int s1= ObjectUtils.defaultIfNull(o1.getSort(),0);
                    int s2= ObjectUtils.defaultIfNull(o2.getSort(),0);
                    return s1-s2;
                })
                .map(categoryEntity -> {
                    categoryEntity.setChildren(getChildren(categoryEntity,all));
                    return categoryEntity;
                })
                .collect(Collectors.toList());
        return root;
    }


    public List<CategoryEntity> getChildren(CategoryEntity root,List<CategoryEntity> all){
        if (root==null){
            return null;
        }
        return all.stream().filter(categoryEntity -> categoryEntity.getParentCid().equals(root.getCatId()))
                .map(categoryEntity -> {
                    categoryEntity.setChildren(getChildren(categoryEntity,all));
                    return categoryEntity;
                }).sorted((o1, o2) -> {
                    int s1= ObjectUtils.defaultIfNull(o1.getSort(),0);
                    int s2= ObjectUtils.defaultIfNull(o2.getSort(),0);
                    return s1-s2;
                })
                .collect(Collectors.toList());
    }

}